/*
 * Created by SharpDevelop.
 * User: GZamor1
 * Date: 7/24/2007
 * Time: 10:37 AM
 * 
 * To change this template use Tools | Options | Coding | Edit Standard Headers.
 */

using System;
using System.Xml;
using System.Collections.Generic;
using MediaPortal.GUI.Library;
using MediaPortal.Configuration;
namespace OnlineVideos
{
	/// <summary>
	/// Description of OnlineVideoSettings.
	/// </summary>
	public class OnlineVideoSettings
	{
		private static OnlineVideoSettings instance = new OnlineVideoSettings();
		public String msThumbLocation;
		public String msDownloadDir;
		public String[] msFilterArray;
        public bool mbForceMPlayer = true;
        public bool mbUseVMR9 = true;
        public const String MPLAYER_EXT = ".mplayer";
		public Dictionary<String,GUIOnlineVideos.SiteSettings> moSiteList = new Dictionary<String, GUIOnlineVideos.SiteSettings>();
		public ITMSClient.TrailerSize AppleTrailerSize = ITMSClient.TrailerSize.h640;
        public String YahooVideoQuality = "500";
        public String YahooTrailerQuality = "500";
		private const String SETTINGS_FILE = "OnlineVideoSites.xml";
		private const String THUMBNAIL_DIR = "thumbDir";
		private const String TRAILER_SIZE = "trailerSize";
		private const String DOWNLOAD_DIR = "downloadDir";
		private const String SECTION = "onlinevideos";
		private const String FILTER = "filter";
        private const String USE_MPLAYER = "useMplayer";
		
		public static OnlineVideoSettings getInstance(){
			if(instance ==null){
				instance = new OnlineVideoSettings();
			}
			return instance;
		}
		private OnlineVideoSettings()
		{
			loadSettings();
		}
		private void loadSettings(){
			String lsTrailerSize;
			using (MediaPortal.Profile.Settings xmlreader = new MediaPortal.Profile.Settings(Config.GetFile(Config.Dir.Config, "MediaPortal.xml")))
			{
				msThumbLocation = xmlreader.GetValueAsString(SECTION, THUMBNAIL_DIR, "");
				
				msDownloadDir = xmlreader.GetValueAsString(SECTION, DOWNLOAD_DIR, "");
                mbForceMPlayer = xmlreader.GetValueAsBool(SECTION, USE_MPLAYER, false);
				String lsFilter = xmlreader.GetValueAsString(SECTION, FILTER, "");
				lsTrailerSize  = xmlreader.GetValueAsString(SECTION,TRAILER_SIZE,"h640");
                mbUseVMR9 = xmlreader.GetValueAsBool("general", "usevrm9forwebstreams", true);
				msFilterArray = lsFilter.Split(new char[] { ',' });
				if (msFilterArray.Length == 1 && msFilterArray[0] == "")
				{
					msFilterArray = null;
				}
			}
			if(Enum.IsDefined(typeof(ITMSClient.TrailerSize),lsTrailerSize)){
				AppleTrailerSize = (ITMSClient.TrailerSize)Enum.Parse(typeof(ITMSClient.TrailerSize),lsTrailerSize,true);
			}
				
			
			if(String.IsNullOrEmpty(msThumbLocation)){
				msThumbLocation = Config.GetFolder(Config.Dir.Thumbs) +@"\OnlineVideos\";
				
			}
			XmlDocument doc = new XmlDocument();
			try
			{
                doc.Load(Config.GetFile(Config.Dir.Config, SETTINGS_FILE));
				
				XmlNode root = doc.SelectSingleNode("//settings/sites/site");
				XmlNodeList nodeList;
				nodeList = root.SelectNodes("//settings/sites/site");
				List<GUIOnlineVideos.SiteSettings> loSiteList = new List<GUIOnlineVideos.SiteSettings>();
				GUIOnlineVideos.SiteSettings loSite;
				XmlNodeList RssNodeList;
				GUIOnlineVideos.RssLink loRssData;
				bool lbDonwloadDirSet = false;
				foreach (XmlNode chileNode in nodeList)
				{
					loSite = new GUIOnlineVideos.SiteSettings();

					XmlNode node = chileNode.SelectSingleNode("name");
					loSite.name = node.InnerText;

					node = chileNode.SelectSingleNode("id");
					loSite.id = node.InnerText;
					
					node = chileNode.SelectSingleNode("user");
					if(node!=null)
						loSite.username = node.InnerText;
					
					node = chileNode.SelectSingleNode("password");
					if(node!=null)
						loSite.password = node.InnerText;
					
					node = chileNode.SelectSingleNode("confirmAge");
					if(node!=null)
						loSite.confirmAge = node.InnerText == "yes";
					
					node = chileNode.SelectSingleNode("enabled");
					if(node!=null)
						loSite.enabled = node.InnerText == "yes";
					
					//Console.WriteLine("site Node:{0}", loSite.ToString());
					RssNodeList = chileNode.SelectNodes("rss");
					foreach (XmlNode RssNode in RssNodeList)
					{
						loRssData = new GUIOnlineVideos.RssLink();
						//node = chileNode.SelectSingleNode("d");

						loRssData.name = RssNode.Attributes["name"].InnerText;
						try{
							loRssData.isDynamic = RssNode.Attributes["dynamic"].InnerText.Equals("yes");
							Log.Info("Found a dynamic category for site {0}",loSite.name);
						}catch(Exception){}
						loRssData.url = RssNode.InnerText;
						if (lbDonwloadDirSet==false && loSite.id == "99")
						{
							msDownloadDir = loRssData.url;
							if(String.IsNullOrEmpty(msDownloadDir)){
								msDownloadDir =
									System.IO.Directory.GetCurrentDirectory()+@"\Downloads\OnlineVideos\";
							}
							if(System.IO.Directory.Exists(msDownloadDir)==false){
								System.IO.Directory.CreateDirectory(msDownloadDir);
							}
							lbDonwloadDirSet = true;
						}
						//Console.WriteLine("rss Node:{0}", loRssData.ToString());
						loSite.RssList.Add(loRssData.name, loRssData);
					}
                    if (SiteUtilFactory.getSiteUtil(loSite.id) != null)
                    {
                        moSiteList.Add(loSite.id, loSite);
                    }
				}
			}
			catch (Exception e)
			{
				//moLog.Error(e);
				Log.Error(e);
			}
		}
		public void saveSettings()
		{
			try
			{
                Log.Info("using MP config file:" + Config.GetFile(Config.Dir.Config, "MediaPortal.xml"));
				using (MediaPortal.Profile.Settings xmlwriter = new MediaPortal.Profile.Settings(Config.GetFile(Config.Dir.Config, "MediaPortal.xml"))) 
				{
                    
					String lsFilterList = "";
					String [] lsFilterArray = msFilterArray;
					if(lsFilterArray!=null){
						foreach (String lsFilter in lsFilterArray){
							lsFilterList+=lsFilter+",";
						}
					}
					if((lsFilterList == ",")==false){
                        lsFilterList.Remove(lsFilterList.Length-1);
						xmlwriter.SetValue(SECTION, FILTER, lsFilterList);
					}else{
						msFilterArray = null;
					}
					xmlwriter.SetValue(SECTION,THUMBNAIL_DIR,msThumbLocation);
                    Log.Info("OnlineVideoSettings - download Dir:" + msDownloadDir);
					xmlwriter.SetValue(SECTION,DOWNLOAD_DIR,msDownloadDir );
					xmlwriter.SetValue(SECTION,TRAILER_SIZE,AppleTrailerSize.ToString());
                    xmlwriter.SetValueAsBool(SECTION, USE_MPLAYER, mbForceMPlayer);
                    Log.Info("saveSettings force mplayer={0}", mbForceMPlayer);                    
				}
				Console.WriteLine(System.IO.Directory.GetCurrentDirectory());
				//pick whatever filename with .xml extension
                string filename = Config.GetFile(Config.Dir.Config, SETTINGS_FILE);
				if(System.IO.File.Exists(filename)){
					System.IO.File.Delete(filename);
				}
				
				XmlDocument xmlDoc = new XmlDocument();

				try
				{
					xmlDoc.Load(filename);
				}
				catch(System.IO.FileNotFoundException)
				{
					//if file is not found, create a new xml file
					XmlTextWriter xmlWriter = new XmlTextWriter(filename, System.Text.Encoding.UTF8);
					xmlWriter.Formatting = Formatting.Indented;
					xmlWriter.WriteProcessingInstruction("xml", "version='1.0' encoding='UTF-8'");
					xmlWriter.WriteStartElement("settings");
					//If WriteProcessingInstruction is used as above,
					//Do not use WriteEndElement() here
					//xmlWriter.WriteEndElement();
					//it will cause the &ltRoot></Root> to be &ltRoot />
					xmlWriter.Close();
					xmlDoc.Load(filename);
				}
				XmlNode root = xmlDoc.DocumentElement;
				
				
				
				XmlElement sitesNode = xmlDoc.CreateElement("sites");
				
				
				XmlElement siteNode;
				XmlElement siteNameNode;
				XmlElement siteIdNode;
				XmlElement siteUserNode;
				XmlElement sitePassNode;
				XmlElement siteConfirmNode;
				XmlElement siteRssNode;
				XmlElement siteEnabledNode;
				String lsConfirm;
				foreach(GUIOnlineVideos.SiteSettings site in moSiteList.Values){
					siteNode = xmlDoc.CreateElement("site");
					
					siteNameNode = xmlDoc.CreateElement("name");
					siteNameNode.InnerText = site.name;
					siteNode.AppendChild(siteNameNode);
					
					siteIdNode = xmlDoc.CreateElement("id");
					siteIdNode.InnerText = site.id;
					siteNode.AppendChild(siteIdNode);
					
					siteUserNode = xmlDoc.CreateElement("user");
					siteUserNode.InnerText = site.username;
					siteNode.AppendChild(siteUserNode);
					
					sitePassNode = xmlDoc.CreateElement("password");
					sitePassNode.InnerText = site.password;
					siteNode.AppendChild(sitePassNode);
					
					siteConfirmNode = xmlDoc.CreateElement("confirm");
					
					if(site.confirmAge){
						lsConfirm = "yes";
					}else{
						lsConfirm = "no";
					}
					
					siteConfirmNode.InnerText = lsConfirm ;
					siteNode.AppendChild(siteConfirmNode);
					
					String lsEnabled;
					if(site.enabled){
						lsEnabled = "yes";
					}else{
						lsEnabled = "no";
					}
					siteEnabledNode = xmlDoc.CreateElement("enabled");
					siteEnabledNode.InnerText = lsEnabled;
					siteNode.AppendChild(siteEnabledNode);
					foreach(GUIOnlineVideos.RssLink link in site.RssList.Values){
						siteRssNode = xmlDoc.CreateElement("rss");
						siteRssNode.SetAttribute("name",link.name);
                        if (link.isDynamic)
                        {
                            siteRssNode.SetAttribute("dynamic", "yes");
                        }
						siteRssNode.AppendChild(xmlDoc.CreateCDataSection(link.url));
						siteNode.AppendChild(siteRssNode);
					}
					sitesNode.AppendChild(siteNode);
				}
				root.AppendChild(sitesNode);
				//root.AppendChild();
				xmlDoc.Save(filename);
			}
			catch(Exception ex)
			{
				Log.Error(ex);
			}
			
			
		}
		/*
		public void oldSaveSettings()
		{
			XmlTextReader loReader = null;
			Log.Info("OnlineVideo Settings: saving settings.");
			try
			{
				string filename = Config.GetFile(Config.Dir.Config, "OnlineVideoSettings.xml");

				loReader = new XmlTextReader(filename);

				XmlDocument xmlDoc = new XmlDocument();

				try
				{
					xmlDoc.Load(loReader);
					loReader.Close();
				}
				catch (System.IO.FileNotFoundException)
				{
					Log.Info("Yahoo Settings: MyMusicVideoSettings.xml not found.");
					//if file is not found, create a new xml file
					//XmlTextWriter xmlWriter = new XmlTextWriter(filename, System.Text.Encoding.UTF8);
					//xmlWriter.Formatting = Formatting.Indented;
					//xmlWriter.WriteProcessingInstruction("xml", "version='1.0' encoding='UTF-8'");
					//xmlWriter.WriteStartElement("FAVOURITES");

					//xmlWriter.Close();
					//xmlDoc.Load(filename);
					return;
				}
				xmlDoc.RemoveAll();
				
				XmlNode root = xmlDoc.DocumentElement;
				//root.
				XmlNodeList xmlNodeList = xmlDoc.GetElementsByTagName("country");

				XmlAttribute defaultAttribute;
				XmlAttribute nameAttribute;
				foreach (XmlNode xmlNode in xmlNodeList)
				{
					nameAttribute = xmlNode.Attributes["name"];

					defaultAttribute = xmlNode.Attributes["default"];

					//Log.Info("name attribute={0}-", nameAttribute.Value);
					//Log.Info("current_country={0}-", msDefaultCountryName);
					if (nameAttribute.Value == msDefaultCountryName)
						defaultAttribute.Value = "Y";
					else
						defaultAttribute.Value = "N";
				}

				xmlNodeList = xmlDoc.GetElementsByTagName("bitrate");

				string lsCurrentBitRate;
				foreach (XmlNode xmlNode in xmlNodeList)
				{
					defaultAttribute = xmlNode.Attributes["default"];
					lsCurrentBitRate = xmlNode.InnerXml;

					if (lsCurrentBitRate == msDefaultBitRate)
						defaultAttribute.Value = "Y";
					else
						defaultAttribute.Value = "N";
				}
				xmlDoc.Save(filename);

				//moFavoriteList.Remove(video);

			}
			catch (Exception e)
			{
				Log.Error(e);
				Log.Info("Yahoo Settings: save settings failed.");
			}
			finally
			{
				try
				{
					loReader.Close();
					Log.Info("Yahoo Settings: save settings - reader closed");
					loReader = null;
				}
				catch (Exception ex)
				{
					Log.Info("Yahoo Settings: Exception - {0}", ex);
				}
			}
			
		}
		 */
	}
}
